﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;

namespace PRO_DOCS.DocumentManagementSystem.ADMIN.WIN.Configurations.Users
{


    public partial class RolesManagement : BLL.WIN.Templates.DevxConfigurationUserControlTemplate
    {
        public DAL.Database.SYSTEM_ROLE SELECTED_SYSTEM_ROLE
        { get; set; }

        public RolesManagement()
        {
            InitializeComponent();

            try
            {
                PRO_DOCSDatabaseDataContext.proc_SYSTEM_AUTHENTICATIONSLoadAll().ToList().ForEach(new Action<PRO_DOCS.DAL.Database.proc_SYSTEM_AUTHENTICATIONSLoadAllResult>(delegate(PRO_DOCS.DAL.Database.proc_SYSTEM_AUTHENTICATIONSLoadAllResult _sYSTEM_AUTHENTICATION)
                {
                    CheckedListBoxItem listViewItem = new CheckedListBoxItem();
                    listViewItem.Value = _sYSTEM_AUTHENTICATION.SYSTEM_AUTHENTICATION_ID.ToString();
                    listViewItem.Description = _sYSTEM_AUTHENTICATION.SYSTEM_AUTHENTICATION_NAME;
                    lstViewRolesAuthentications.Items.Add(listViewItem);
                }));
            }
            catch { }

            btnAddNew.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnAddNew_ItemClick);
            btnSaveUpdate.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnSaveUpdate_ItemClick);
            btnRefresh.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnRefresh_ItemClick);
            btnDeleteItem.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnDeleteItem_ItemClick);
        }

        private void btnDeleteItem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (SELECTED_SYSTEM_ROLE != null)
            {
                if (SELECTED_SYSTEM_ROLE.IS_EDITABLE.Value)
                {


                    if (XtraMessageBox.Show("Are you sure you want to delete the current role?", "Confirm delete", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2).Equals(DialogResult.Yes))
                    {
                        try
                        {
                            PRO_DOCSDatabaseDataContext.proc_LOGIN_USERSDelete(SELECTED_SYSTEM_ROLE.ROLE_ID);
                            gridView1.DeleteSelectedRows();
                        }
                        catch
                        {
                            XtraMessageBox.Show("The selected role cannot be deleted as it is already used in another transaction(s)", "Action denied", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
                else
                {
                    XtraMessageBox.Show("This role is a system role and can't be modified.", "deleting terminated", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
            }
        }

        private void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            LOAD_ALL_SYSTEM_ROLES();
        }

        private void btnSaveUpdate_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            dxErrorProvider1.ClearErrors();
            bool continue_saving = true;

            bool isEditable = SELECTED_SYSTEM_ROLE.IS_EDITABLE.Value;
            bool hasRoleName = !string.IsNullOrEmpty(txtRoleName.Text);

            continue_saving = isEditable && hasRoleName;

            if (continue_saving)
            {
                if (SELECTED_SYSTEM_ROLE.ROLE_ID > 0)//already existed user
                {
                    PRO_DOCSDatabaseDataContext.proc_SYSTEM_ROLESUpdate
                        (SELECTED_SYSTEM_ROLE.ROLE_ID,
                        txtRoleName.Text,
                        chkIsEditable.Checked,
                        !chkIsActiveLogin.Checked
                        );

                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcRoleName, txtRoleName.Text);
                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcIsEditable, chkIsEditable.Checked);
                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcIsActive, !chkIsActiveLogin.Checked);

                    ADD_LOGIN_USER_ROLES();
                }
                else //insert a new user
                {
                    long? new_system_role = 0;

                    PRO_DOCSDatabaseDataContext.proc_SYSTEM_ROLESInsert
                        (ref new_system_role,
                        txtRoleName.Text,
                        chkIsEditable.Checked,
                        !chkIsActiveLogin.Checked);

                    SELECTED_SYSTEM_ROLE = (from users in PRO_DOCSDatabaseDataContext.SYSTEM_ROLEs
                                            where users.ROLE_ID.Equals(new_system_role.Value)
                                            select users).FirstOrDefault();


                    ADD_LOGIN_USER_ROLES();
                    LOAD_ALL_SYSTEM_ROLES();
                }
            }
            else
            {
                if (!isEditable)
                {
                    XtraMessageBox.Show("This role is a system role and can't be modified.", "Saving terminated", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                if (!hasRoleName)
                {
                    dxErrorProvider1.SetError(txtRoleName, BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "Role name"));
                }
            }
        }

        private void ADD_LOGIN_USER_ROLES()
        {
            //1. delete old data
            PRO_DOCSDatabaseDataContext.proc_SYSTEM_ROLES_AUTHENTICATIONSDeleteByROLE_ID
                (SELECTED_SYSTEM_ROLE.ROLE_ID);

            for (int i = 0; i < lstViewRolesAuthentications.Items.Count; i++)
            {
                if (lstViewRolesAuthentications.GetItemChecked(i))
                {
                    PRO_DOCSDatabaseDataContext.proc_SYSTEM_ROLES_AUTHENTICATIONSInsert
                        (
                            SELECTED_SYSTEM_ROLE.ROLE_ID,
                            Convert.ToInt64(lstViewRolesAuthentications.GetDisplayItemValue(i).ToString())
                        );
                }
            }
        }

        private void btnAddNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SELECTED_SYSTEM_ROLE = new DAL.Database.SYSTEM_ROLE();
            SELECTED_SYSTEM_ROLE.IS_DELETED = false;
            SELECTED_SYSTEM_ROLE.IS_EDITABLE = true;

            txtRoleName.Text = string.Empty;
            chkIsEditable.Checked = true;
            chkIsActiveLogin.Checked = false;

            lstViewRolesAuthentications.UnCheckAll();


            gridView1.UnselectRow(gridView1.FocusedRowHandle);
            gridView1.ClearSelection();
        }

        private void LOAD_LOGIN_USER_ROLES()
        {
            Dictionary<long, PRO_DOCS.DAL.Database.proc_SYSTEM_ROLES_AUTHENTICATIONSLoadAllByROLE_IDResult> lOGIN_USER_ROLES = PRO_DOCSDatabaseDataContext.proc_SYSTEM_ROLES_AUTHENTICATIONSLoadAllByROLE_ID(SELECTED_SYSTEM_ROLE.ROLE_ID).ToDictionary(k => k.SYSTEM_AUTHENTICATION_ID, v => v);

            for (int i = 0; i < lstViewRolesAuthentications.Items.Count; i++)
            {
                bool item_checked = lOGIN_USER_ROLES.ContainsKey(Convert.ToInt64(lstViewRolesAuthentications.GetDisplayItemValue(i).ToString()));
                lstViewRolesAuthentications.SetItemChecked(i, item_checked);
            }
        }

        private void UserManagement_Load(object sender, EventArgs e)
        {
            LOAD_ALL_SYSTEM_ROLES();
        }

        private void LOAD_ALL_SYSTEM_ROLES()
        {
            List<DAL.Database.SYSTEM_ROLE> sYSTEM_ROLE = PRO_DOCSDatabaseDataContext.SYSTEM_ROLEs.ToList();

            //sYSTEM_ROLE[0].
            //for (int i = 0; i < sYSTEM_ROLE.Count; i++)
            //{
            //    UserManagemntList sINGLE_LOGIN_USER = new UserManagemntList();

            //    sINGLE_LOGIN_USER.IsValid = sYSTEM_ROLE[i].IS_ACTIVE_USER.Value.ToString().ToLower();

            //    sINGLE_LOGIN_USER.LOGIN_USER = sYSTEM_ROLE[i];

            //    LOGIN_USERS.Add(sINGLE_LOGIN_USER);
            //}

            lstViewUsers.DataSource = sYSTEM_ROLE;

            gridView1.SelectRow(0);


        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            dxErrorProvider1.ClearErrors();

            if (e.FocusedRowHandle > -1)
            {
                DAL.Database.SYSTEM_ROLE cURRENT_SELECTED_SYSTEM_ROLE = gridView1.GetFocusedRow() as DAL.Database.SYSTEM_ROLE;

                SELECTED_SYSTEM_ROLE = cURRENT_SELECTED_SYSTEM_ROLE;

                txtRoleName.Text = SELECTED_SYSTEM_ROLE.ROLE_NAME;
                chkIsEditable.Checked = SELECTED_SYSTEM_ROLE.IS_EDITABLE.Value;
                chkIsActiveLogin.Checked = SELECTED_SYSTEM_ROLE.IS_DELETED.Value;


                LOAD_LOGIN_USER_ROLES();
            }
        }

        private void chkAllowExpiry_CheckedChanged(object sender, EventArgs e)
        {
            if (chkAllowExpiry.Checked)
            {
                dtpkrExpiryDate.Enabled = false;
                dtpkrExpiryDate.EditValue = null;
            }
            else
            {
                dtpkrExpiryDate.Enabled = true;
                dtpkrExpiryDate.EditValue = DateTime.Now;
            }
        }
    }
}
